<template>
  <div class="role-list">
    <div class="page-header">
      <h1>角色管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openRoleForm()">
          <el-icon><Plus /></el-icon> 新增角色
        </el-button>
      </div>
    </div>

    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="roles"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="180" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="userCount" label="用户数" width="100" />
        <el-table-column label="系统角色" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.isSystem ? 'success' : 'info'"
              size="small"
            >
              {{ scope.row.isSystem ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              text
              @click="openRoleForm(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="primary"
              text
              @click="viewRoleDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="danger"
              text
              @click="confirmDeleteRole(scope.row)"
              :disabled="scope.row.userCount > 0"
              :title="scope.row.userCount > 0 ? '请先移除关联的用户' : ''"
            >
              删除
            </el-button>
            <el-tooltip
              v-if="scope.row.userCount > 0"
              effect="dark"
              content="该角色已关联用户，请先移除关联用户再删除"
              placement="top"
            >
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="roleFormVisible"
      :title="isEditMode ? '编辑角色' : '新增角色'"
      width="650px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="权限分配" prop="permissionIds">
          <div class="permissions-container">
            <el-collapse accordion>
              <el-collapse-item
                v-for="(permissionGroup, groupName) in groupedPermissions"
                :key="groupName"
                :title="getGroupDisplayName(groupName)"
                :name="groupName"
              >
                <div class="permission-group">
                  <el-checkbox
                    v-model="groupCheckAll[groupName]"
                    :indeterminate="groupIndeterminate[groupName]"
                    @change="val => handleCheckAllChange(val, groupName)"
                  >
                    全选
                  </el-checkbox>
                  <div class="permission-list">
                    <el-checkbox-group
                      v-model="roleForm.permissionIds"
                      @change="handleCheckedPermissionsChange"
                    >
                      <el-checkbox
                        v-for="permission in permissionGroup"
                        :key="permission.id"
                        :label="permission.id"
                        class="permission-item"
                      >
                        {{ permission.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色详情对话框 -->
    <el-dialog v-model="roleDetailVisible" title="角色详情" width="650px">
      <div v-if="currentRole" class="role-detail">
        <div class="detail-item">
          <span class="label">ID：</span>
          <span>{{ currentRole.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">角色名称：</span>
          <span>{{ currentRole.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <span>{{ currentRole.description || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">系统角色：</span>
          <el-tag :type="currentRole.isSystem ? 'success' : 'info'" size="small">
            {{ currentRole.isSystem ? '是' : '否' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span>{{ formatDateTime(currentRole.createdAt) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span>{{ formatDateTime(currentRole.updatedAt) }}</span>
        </div>
        
        <div class="detail-section">
          <h3>权限列表</h3>
          <el-collapse>
            <el-collapse-item
              v-for="(permissions, group) in rolePermissionsByGroup"
              :key="group"
              :title="getGroupDisplayName(group)"
              :name="group"
            >
              <div class="permission-tags">
                <el-tag
                  v-for="permission in permissions"
                  :key="permission.id"
                  class="permission-tag"
                >
                  {{ permission.name }}
                </el-tag>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        
        <div v-if="currentRole.users && currentRole.users.length > 0" class="detail-section">
          <h3>关联用户 ({{ currentRole.users.length }})</h3>
          <div class="user-list">
            <el-table :data="currentRole.users" border style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="180" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-popconfirm
                    title="确认解除该用户与当前角色的关联?"
                    @confirm="unlinkUserFromRole(currentRole.id, scope.row.id)"
                  >
                    <template #reference>
                      <el-button size="small" type="danger" text>
                        解除关联
                      </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, InfoFilled } from '@element-plus/icons-vue';
import { getRoles, getPermissions, createRole, updateRole, deleteRole, getRoleById } from '@/api/role';
import { formatDateTime } from '@/utils/format';

// 角色列表数据
const roles = ref([]);
const loading = ref(false);
const submitting = ref(false);

// 权限数据
const permissions = ref([]);
const groupedPermissions = ref({});
const activePermissionTab = ref('');

// 权限分组英文到中文的映射
const permissionGroupMap = {
  'categories': '分类',
  'departments': '部门',
  'orders': '订单',
  'products': '商品',
  'reports': '报表',
  'roles': '角色',
  'settings': '设置',
  'system': '系统',
  'users': '用户'
};

// 获取分组的中文名称
const getGroupDisplayName = (groupName) => {
  return permissionGroupMap[groupName] || groupName;
};

// 表单相关
const roleFormVisible = ref(false);
const roleFormRef = ref(null);
const isEditMode = ref(false);
const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  permissionIds: []
});

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
};

// 全选相关
const groupCheckAll = ref({});
const groupIndeterminate = ref({});

// 角色详情
const roleDetailVisible = ref(false);
const currentRole = ref(null);

// 根据分组整理当前角色的权限
const rolePermissionsByGroup = computed(() => {
  if (!currentRole.value || !currentRole.value.permissions) {
    return {};
  }
  
  const result = {};
  currentRole.value.permissions.forEach(permission => {
    if (!result[permission.group]) {
      result[permission.group] = [];
    }
    result[permission.group].push(permission);
  });
  
  return result;
});

// 加载角色列表
const loadRoles = async () => {
  loading.value = true;
  try {
    console.log('正在获取角色列表...');
    const response = await getRoles();
    console.log('获取角色列表响应:', response);
    
    // 检查响应格式，确保可以正确读取数据
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        // 直接是数组格式
        roles.value = response.data;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        // 嵌套在data字段中的数组
        roles.value = response.data.data;
      } else {
        console.error('获取角色列表：响应格式不正确', response.data);
        roles.value = [];
        ElMessage.error('角色数据格式不正确');
      }
    } else {
      console.error('获取角色列表：响应为空');
      roles.value = [];
      ElMessage.error('获取角色列表失败：响应为空');
    }
  } catch (error) {
    console.error('获取角色列表失败', error);
    roles.value = [];
    ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 加载权限列表
const loadPermissions = async () => {
  try {
    console.log('正在获取权限列表...');
    const response = await getPermissions();
    console.log('获取权限列表响应:', response);
    
    // 检查响应格式，确保可以正确读取数据
    if (response && response.data) {
      if (response.data.status === 'success' && response.data.data) {
        // 权限在API成功响应的data字段中
        groupedPermissions.value = response.data.data;
      } else if (typeof response.data === 'object' && !Array.isArray(response.data)) {
        // 权限直接在data对象中
        groupedPermissions.value = response.data;
      } else {
        console.error('获取权限列表：响应格式不正确', response.data);
        groupedPermissions.value = {};
        ElMessage.error('权限数据格式不正确');
      }
    } else {
      console.error('获取权限列表：响应为空');
      groupedPermissions.value = {};
      ElMessage.error('获取权限列表失败：响应为空');
    }
    
    console.log('分组后的权限数据:', groupedPermissions.value);
    
    // 初始化全选状态
    Object.keys(groupedPermissions.value).forEach(group => {
      groupCheckAll.value[group] = false;
      groupIndeterminate.value[group] = false;
    });
    
    // 设置默认活动项为第一个分组
    if (Object.keys(groupedPermissions.value).length > 0) {
      activePermissionTab.value = Object.keys(groupedPermissions.value)[0];
    }
  } catch (error) {
    console.error('获取权限列表失败', error);
    groupedPermissions.value = {};
    ElMessage.error('获取权限列表失败: ' + (error.message || '未知错误'));
  }
};

// 打开角色表单
const openRoleForm = (role = null) => {
  resetRoleForm();
  
  if (role) {
    isEditMode.value = true;
    roleForm.id = role.id;
    roleForm.name = role.name;
    roleForm.description = role.description || '';
    
    // 获取详细角色信息，包括权限
    getRoleDetail(role.id);
  } else {
    isEditMode.value = false;
    roleFormVisible.value = true;
  }
};

// 获取角色详情
const getRoleDetail = async (id) => {
  try {
    console.log('正在获取角色详情...');
    const response = await getRoleById(id);
    console.log('获取角色详情响应:', response);
    
    // 处理嵌套响应格式
    let roleData;
    if (response && response.data) {
      if (response.data.status === 'success' && response.data.data) {
        // API成功响应格式 {status: 'success', data: {...}}
        roleData = response.data.data;
      } else {
        // 直接在data中
        roleData = response.data;
      }
    } else {
      throw new Error('无效的响应数据');
    }
    
    console.log('处理后的角色数据:', roleData);
    
    // 确保permissions是数组
    if (!Array.isArray(roleData.permissions)) {
      console.error('权限数据不是数组格式:', roleData.permissions);
      roleData.permissions = [];
    }
    
    // 设置权限ID
    roleForm.permissionIds = roleData.permissions.map(p => p.id);
    
    // 更新每个分组的全选状态
    updateGroupCheckStatus();
    
    roleFormVisible.value = true;
  } catch (error) {
    console.error('获取角色详情失败', error);
    ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'));
  }
};

// 查看角色详情
const viewRoleDetail = async (role) => {
  try {
    console.log('正在查看角色详情...');
    const response = await getRoleById(role.id);
    console.log('查看角色详情响应:', response);
    
    // 处理嵌套响应格式
    if (response && response.data) {
      if (response.data.status === 'success' && response.data.data) {
        // API成功响应格式 {status: 'success', data: {...}}
        currentRole.value = response.data.data;
      } else {
        // 直接在data中
        currentRole.value = response.data;
      }
    } else {
      throw new Error('无效的响应数据');
    }
    
    console.log('当前角色数据:', currentRole.value);
    roleDetailVisible.value = true;
  } catch (error) {
    console.error('获取角色详情失败', error);
    ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'));
  }
};

// 提交角色表单
const submitRoleForm = async () => {
  if (!roleFormRef.value) return;
  
  await roleFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    try {
      if (isEditMode.value) {
        await updateRole(roleForm.id, {
          name: roleForm.name,
          description: roleForm.description,
          permissionIds: roleForm.permissionIds
        });
        ElMessage.success('角色更新成功');
      } else {
        await createRole({
          name: roleForm.name,
          description: roleForm.description,
          permissionIds: roleForm.permissionIds
        });
        ElMessage.success('角色创建成功');
      }
      
      roleFormVisible.value = false;
      loadRoles();
    } catch (error) {
      console.error('保存角色失败', error);
      ElMessage.error('保存角色失败: ' + (error.response?.data?.message || error.message));
    } finally {
      submitting.value = false;
    }
  });
};

// 确认删除角色
const confirmDeleteRole = (role) => {
  // 构建删除风险提示信息
  const warningMessage = `
    <div class="delete-warning">
      <p><strong>确定要删除角色 "${role.name}" 吗？</strong></p>
      <p class="warning-title">请注意以下风险：</p>
      <ul>
        <li>此操作将<span class="text-danger">永久删除</span>该角色，无法恢复</li>
        <li>该角色的所有权限配置将丢失</li>
        <li>如果有用户关联此角色，需要先解除关联才能删除</li>
      </ul>
      <p class="warning-footer">建议在删除前先备份相关数据</p>
    </div>
  `;

  ElMessageBox.confirm(
    warningMessage,
    '删除角色风险警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      confirmButtonClass: 'el-button--danger'
    }
  )
    .then(async () => {
      try {
        await deleteRole(role.id);
        ElMessage.success('角色删除成功');
        loadRoles();
      } catch (error) {
        console.error('删除角色失败', error);
        ElMessage.error('删除角色失败: ' + (error.response?.data?.message || error.message));
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除操作');
    });
};

// 重置角色表单
const resetRoleForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
  
  roleForm.id = null;
  roleForm.name = '';
  roleForm.description = '';
  roleForm.permissionIds = [];
  
  // 重置分组选择状态
  Object.keys(groupCheckAll.value).forEach(group => {
    groupCheckAll.value[group] = false;
    groupIndeterminate.value[group] = false;
  });
};

// 处理全选变化
const handleCheckAllChange = (val, group) => {
  if (!groupedPermissions.value[group]) return;
  
  // 获取当前分组的所有权限ID
  const groupPermissionIds = groupedPermissions.value[group].map(p => p.id);
  
  // 如果全选，添加所有权限ID；否则，移除所有权限ID
  if (val) {
    // 先创建一个新的权限ID集合，包含原有的和当前分组的
    const newPermissionIds = [
      ...roleForm.permissionIds.filter(id => !groupPermissionIds.includes(id)),
      ...groupPermissionIds
    ];
    roleForm.permissionIds = newPermissionIds;
  } else {
    // 移除当前分组的所有权限ID
    roleForm.permissionIds = roleForm.permissionIds.filter(
      id => !groupPermissionIds.includes(id)
    );
  }
  
  groupIndeterminate.value[group] = false;
};

// 处理权限选择变化
const handleCheckedPermissionsChange = () => {
  updateGroupCheckStatus();
};

// 更新分组选择状态
const updateGroupCheckStatus = () => {
  Object.keys(groupedPermissions.value).forEach(group => {
    const groupPermissionIds = groupedPermissions.value[group].map(p => p.id);
    const checkedCount = roleForm.permissionIds.filter(id => 
      groupPermissionIds.includes(id)
    ).length;
    
    groupCheckAll.value[group] = checkedCount === groupPermissionIds.length;
    groupIndeterminate.value[group] = checkedCount > 0 && checkedCount < groupPermissionIds.length;
  });
};

// 添加解除用户与角色关联的方法
// 解除用户与角色的关联
const unlinkUserFromRole = async (roleId, userId) => {
  try {
    // 这里需要调用后端API来解除关联
    // 假设我们有一个解除关联的API
    const response = await fetch(`http://localhost:3000/api/users/${userId}/roles/${roleId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '操作失败');
    }
    
    ElMessage.success('用户角色关联已解除');
    
    // 刷新角色详情
    const updatedRoleResponse = await getRoleById(roleId);
    if (updatedRoleResponse && updatedRoleResponse.data && updatedRoleResponse.data.data) {
      currentRole.value = updatedRoleResponse.data.data;
    }
    
    // 刷新角色列表
    await loadRoles();
  } catch (error) {
    console.error('解除用户角色关联失败:', error);
    ElMessage.error('解除用户角色关联失败: ' + error.message);
  }
};

onMounted(async () => {
  await loadPermissions();
  await loadRoles();
});
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.permissions-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.permission-group {
  margin-bottom: 5px;
}

.permission-list {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  padding-left: 10px;
}

.permission-item {
  margin-right: 12px;
  margin-bottom: 8px;
  flex: 0 0 auto;
  min-width: 120px;
}

.role-detail .detail-item {
  margin-bottom: 12px;
  display: flex;
}

.role-detail .label {
  font-weight: bold;
  min-width: 100px;
}

.detail-section {
  margin-top: 20px;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 5px 0;
}

.permission-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 自定义折叠面板样式 */
:deep(.el-collapse-item__header) {
  font-weight: bold;
  color: #409eff;
  background-color: #f5f7fa;
  padding-left: 10px;
}

:deep(.el-collapse-item__content) {
  padding: 10px;
}

:deep(.el-collapse) {
  border: none;
}

.info-icon {
  color: #F56C6C;
  margin-left: 5px;
  cursor: pointer;
}

.delete-warning {
  text-align: left;
  margin-top: 10px;
}

.warning-title {
  font-weight: bold;
  margin-top: 10px;
  color: #E6A23C;
}

.warning-footer {
  font-style: italic;
  margin-top: 10px;
  color: #909399;
}

.text-danger {
  color: #F56C6C;
  font-weight: bold;
}
</style> 